package serial

fun Byte.toU8() = this.toInt() and 0xFF

inline fun encodeU8(buf: ByteArray, offset: Int, value: Int) {
    buf[offset] = value.toByte()
}

inline fun encodeU16(buf: ByteArray, offset: Int, value: Int) {
    buf[offset] = (value shr 8).toByte()
    buf[offset + 1] = value.toByte()
}

inline fun encodeU32(buf: ByteArray, offset: Int, value: Int) {
    buf[offset] = (value shr 24).toByte()
    buf[offset + 1] = (value shr 16).toByte()
    buf[offset + 2] = (value shr 8).toByte()
    buf[offset + 3] = value.toByte()
}

inline fun decodeU8(buf: ByteArray, offset: Int): Int {
    return buf[offset].toInt() and 0xFF
}

inline fun decodeU16(buf: ByteArray, offset: Int): Int {
    return ((buf[offset].toInt() and 0xFF) shl 8) +
            (buf[offset + 1].toInt() and 0xFF)
}

inline fun decodeU32(buf: ByteArray, offset: Int): Int {
    return ((buf[offset].toInt() and 0xFF) shl 24) +
            ((buf[offset + 1].toInt() and 0xFF) shl 16) +
            ((buf[offset + 2].toInt() and 0xFF) shl 8) +
            (buf[offset + 3].toInt() and 0xFF)
}



